Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

269
Vistas
Javascript - How can I build a sentence to display data based on whether data values are > 0?

I am getting back data from an API - just an object with numerical values pertaining to each key - and then building a simple sentence to display the data for the user. However, I only want to include a value from the data if it is bigger than 0. Here is an example with mock data:

let data = {red: 100, blue: 200, yellow: 0, green: 400};

let resultsSentence = `We found ${data.red} red posts, ${data.blue} blue posts, and ${data.green} green posts.`

console.log(resultsSentence)

As you can see, I left yellow out from the results sentence because it has a value of 0. Of course, I need to be able to generate this sentence dynamically based on whatever data is returned. If I use conditionals, it will be a mess, since there are too many possible scenarios (writing 15 if/else statements does not seem like a good approach).

How can I handle this? I need to generate the sentence based on whichever values are > 0. At first I thought, easy, I'll just push all the values into an array, check for 0's, and remove any items that are equal to 0 from the array. Then, build the sentence based on however long the array is, i.e., if the array length is 3, then refer to each value as array[0], array[1], array[2]. However, this presents a problem, since I need to be able to clarify which values are which in the sentence. For example, if I remove yellow from the array, the array length will be 3, but I won't know which value was removed.

Can anyone help me come up with an efficient solution for this?

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You can use a simple for..of loop to iterate over the object's keys and values, building up your string inside of it.

This does result in an oxford comma but you can strip that in the conditional (where you choose to use and instead).

let data = {red: 100, blue: 200, yellow: 0, green: 400};
let res = 'We found '

// Keep a record of how many keys we've processed so we know when we're at the end
let i = 1
for (const [k, v] of Object.entries(data)) {
  // we could just continue early here, but we want to keep adding to `i`
  if (v > 0) { 
    // This is the last key so use `and` not a comma
    if (i === Object.keys(data).length) {
      res += `and ${v} ${k} posts.`
    } else {
      res += `${v} ${k} posts, `
    }
  }
  i++
}

console.log(res)

about 4 years ago · Juan Pablo Isaza Denunciar

0

Try this

let data = {red: 100, blue: 200, yellow: 0, green: 400};

let str = [];
let len = Object.keys(data).length;
Object.entries(data).forEach(([key, val], index) => {
    let isLast = (len - 1 == index) && str.length > 0;
    if(val > 0) str.push((isLast ? 'and ' : '') + `${val} ${key} posts`);
})

let resultsSentence = 'We found ' + str.join(', ')
console.log(resultsSentence)

about 4 years ago · Juan Pablo Isaza Denunciar

0

try this (without depedencies)

const keys = Object.keys(data)
const values = Object.values(data)
let string = 'we found'

values.map((item, index)=>{
  if(item > 0){
        string += ` ${item} ${keys[index]} posts,`
  }
})
console.log(string.slice(0,-1)+'.')

try with lodash as

const _ = require('lodash')

let data = {red: 100, blue: 200, yellow: 0, green: 400};
let string = 'we found'

_.map(data,(value,key)=>{
  if(value > 0){
    string += ` ${value} ${key} posts,`
  }
})
console.log(string.slice(0,-1)+'.')
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda